package com.etang.shtest;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bizideal.smarthome.socket.Utils.SpUtils;
import com.etang.shtest.dialogs.DialogDebugs;
import com.etang.shtest.tools.AppConfig;
import com.etang.shtest.tools.MyDataBaseHelper;
import com.etang.shtest.tools.MySQLiteHelper;

import java.util.Locale;

/**
 * APP主入口、登录界面
 */
public class MainActivity extends AppCompatActivity {
    //数据库
    private MyDataBaseHelper dbHelper;
    private SQLiteDatabase db;
    //进度条
    private SeekBar sk_loading;
    //文本
    private TextView tv_loading_number;
    //进度
    private int number = 0;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions();//动态权限申请
        initView();//绑定控件
        initOpen();//检查是否第一次打开
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void setLanguage() {
        //读取SharedPreferences数据，默认选中第一项
        int language = Integer.valueOf(SpUtils.getValue(getApplicationContext(), "language", null));
        //根据读取到的数据，进行设置
        Resources resources = getResources();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        switch (language) {
            case 0:
                //自动获取
                configuration.setLocale(Locale.getDefault());
                break;
            case 1:
                //中文
                configuration.setLocale(Locale.CHINESE);
                break;
            case 2:
                //英文
                configuration.setLocale(Locale.ENGLISH);
                break;
            case 3:
                //日文
                configuration.setLocale(Locale.JAPANESE);
                break;
            default:
                break;
        }
        resources.updateConfiguration(configuration, displayMetrics);
    }


    /**
     * 绑定控件
     */
    private void initView() {
        //数据库
        dbHelper = new MyDataBaseHelper(getApplicationContext(), "info.db", null, 2);
        db = dbHelper.getWritableDatabase();
        //绑定文本、进度条
        sk_loading = (SeekBar) findViewById(R.id.sk_loading);
        tv_loading_number = (TextView) findViewById(R.id.tv_loading_number);
    }

    /**
     * 加载进度条的线程
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            sk_loading.setProgress(number);
            tv_loading_number.setText(getString(R.string.loading) + number + "%");
            if (number == 100) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                overridePendingTransition(0, 0);//关闭跳转动画
                finish();
            }
            handler.postDelayed(timeRunna, 1);
        }
    };
    Runnable timeRunna = new Runnable() {
        @Override
        public void run() {
            number++;
            Message msg = handler.obtainMessage();
            if (number > 100) {
                handler.removeCallbacks(timeRunna);
            } else {
                handler.sendMessage(msg);
            }
        }
    };

    /**
     * 检查是否第一次打开
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void initOpen() {
        try {
            //判断SpUtilt内是否含有数据或者是否创建。当此段报错时，则一定是SpUtils没有被使用过，重新调用一遍即可
            if (SpUtils.getValue(MainActivity.this, "is_open", null).equalsIgnoreCase("0")
                    || SpUtils.getValue(MainActivity.this, "is_open", null).isEmpty()) {
                SpUtils.putValue(MainActivity.this, "is_open", "1");
                initData();//插入数据
                startActivity(new Intent(MainActivity.this, WeleComeActivity.class));
                overridePendingTransition(0, 0);//关闭跳转动画
                finish();
            } else {
                setLanguage();//读取语言设置
                AppConfig.getBORDID(MainActivity.this);
                handler.post(timeRunna);//开启加载线程
            }
        } catch (Exception e) {
            initData();//插入数据
            startActivity(new Intent(MainActivity.this, WeleComeActivity.class));
            overridePendingTransition(0, 0);//关闭跳转动画
            finish();
        }
    }

    /**
     * 插入数据
     */
    private void initData() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //插入1，即不是第一次打开APP
                    SpUtils.putValue(MainActivity.this, "is_open", "1");
                    //向数据库插入默认指令
                    MySQLiteHelper.modeinsert(MainActivity.this);
                    //记住密码、自动登录默认关闭状态
                    SpUtils.putValue(getApplicationContext(), "autologin", "0");
                    SpUtils.putValue(getApplicationContext(), "rember", "0");
                    //默认填充自动语言设置
                    SpUtils.putValue(getApplicationContext(), "language", "0");
                    //初始化设备版号
                    AppConfig.initBORDID(MainActivity.this);
                }
            }).start();
        } catch (Exception e) {
            DialogDebugs.showdialog(MainActivity.this, "MainActivity.class", e.toString());
        }
    }

    /**
     * 动态权限申请
     */
    private void requestPermissions() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int permission = ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.LOCATION_HARDWARE,
                            Manifest.permission.WRITE_SETTINGS, Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO}, 0x0010);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}